const ArticleService = require('@/service/article');

const mimeTypes = require('mime-types');

const {blog_tag} = require('@/model')

const Response = require('@/utils/response');
const { sequelize } = require('@/model');
const qiniuService = require('@/service/upload');
class ArticleController {

  async getArticleList(ctx) {
    try {
      const res = await ArticleService.getArticleList(ctx.request.body);
      if (res) {
        return Response.success(ctx, res,'获取文章列表成功');
      } else {
        return Response.error(ctx, '获取文章列表失败', 500);
      }
    } catch (error) {
      return Response.error(ctx, '获取文章列表失败', 500, error);
    }
  }

  async getArticleDetail(ctx) {
    try {
      const res = await ArticleService.getArticleDetail(ctx.params.id);
      if (res) {
        return Response.success(ctx, res, '获取文章详情成功');
      } else {
        return Response.error(ctx, '获取文章详情失败', 500);
      }
    } catch (error) {
      return Response.error(ctx, '获取文章详情失败', 500, error);
    }
  }
  async addArticle(ctx) {
    try {
      const { tagList=[], ...params } = ctx.request.body;
      if (!params.title) {
        return Response.error(ctx, '文章标题不能为空', 400);
      }
      if (!params.content) {
        return Response.error(ctx, '文章内容不能为空', 400);
      }
      // 创建标签
      const tagPromises = tagList.map(async (tagName) => { 
        const [tagInstance] = await blog_tag.findOrCreate({ where: { name: tagName } }); // 查找或创建标签
        return tagInstance;
      });
      const tagInstances = await Promise.all(tagPromises);
      // 添加文章
      const newArticle = await ArticleService.addArticle(params);
      if (!newArticle) {
        return Response.error(ctx, '添加文章失败', 500);
      }
      await newArticle.setTags(tagInstances);
      return Response.success(ctx, newArticle, '添加文章成功');
    } catch (error) {
      return Response.error(ctx, '添加文章失败', 500, error);
    }
  }
  async saveArticle(ctx) {
    try {
      const {cover,...params} = ctx.request.body;
      const files = ctx.request.files || ctx.request.body.files;
      const { id } = ctx.state.user; // 获取用户信息
      let coverImageUrl = cover; // 封面图片地址
      // 1. 处理图片上传
      if (files && files.cover) {
        const file = files.cover;

        // 验证文件类型
        const mimeType = mimeTypes.lookup(file.originalFilename);
        if (!mimeType.startsWith('image/')) {
          return Response.error(ctx, '仅支持上传图片格式的文件', 415);
        }

        // 验证文件大小（10MB）
        if (file.size > 10 * 1024 * 1024) {
          throw { status: 413, message: '文件大小不能超过10MB' };
        }
        // 上传到七牛云
        coverImageUrl = await qiniuService.uploadStream(
          file.filepath,
          file.originalFilename
        );
      }
      if (params.id) { // 修改
        params.update_user = id;
      } else { // 新增
        params.author_id = id;
      }
      params.cover = coverImageUrl;
      const res = await ArticleService.saveArticle(params);
      if (res) {
        return Response.success(ctx, res, '保存文章成功');
      } else {
        return Response.error(ctx, '保存文章失败', 500);
      }
    } catch (error) {
      return Response.error(ctx, '保存文章失败', 500, error);
    }
  }
  async deleteArticle(ctx) {
    try {
      const { id } = ctx.request.body;
      const result = await ArticleService.deleteArticle(id);
      if (result) {
        return Response.success(ctx, result, '删除文章成功');
      } else {
        return Response.error(ctx, '删除文章失败', 500);
      }
    } catch (error) {
      return Response.error(ctx, '删除文章失败', 500, error);
    }
  }
}

module.exports = new ArticleController();